<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {margin: 0;overflow: hidden;}
    #canvas {background-color: antiquewhite;}
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    /** @type {HTMLCanvasElement} */
    const canvas = document.querySelector('#canvas');
    const [width, height] = [window.innerWidth, window.innerHeight];
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');

    /*小球对象
      x、y 位置
      draw(ctx)绘图方法
    */
    class Ball {
      constructor(x=0,y=0) {
        this.x = x;
        this.y = y;
      }
      draw(ctx) {
        const {x,y} = this;
        ctx.save();
        ctx.beginPath();
        ctx.arc(x,y,15,0,Math.PI*2);
        ctx.fill();
        ctx.restore();
      }
    }

    /* 实例化小球 */
    const ball = new Ball(300,100);
    ball.draw(ctx);


    /*速度 vy(像素/毫秒) */
    let vy = 0.2;

    /* 加速度 */
    const ay = 0.02;

    // 弹力
    const bounce = 0.8;

    // 计时器
    let time = new Date();

    /*请求动画帧*/
    !(function render(){
      // 当前时间
      const now = new Date();
      // 时间差 (毫秒单位时间长度)
      const diff = now - time;
      time = now;
      // console.log('diff',diff);
      // 清除画布
      ctx.clearRect(0,0,canvas.width,canvas.height);
      // 移动
      // ball.y += vy; // 帧动画时间差 参差不齐
      // ball.y += vy * diff; // 匀速运动
      vy += ay; // 加速度
      ball.y += vy * diff;

      // 判断与地面的碰撞
      if (ball.y + 15 > height) {
        ball.y = height-15;
        vy *= -bounce;
      }

      ball.draw(ctx);
      /* if (ball.y > height) {
        ball.y = 0;
      } */
      requestAnimationFrame(render);
    })();


  </script>
</body>
</html>